#coding=utf-8
import smtplib,os,time
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import datetime

now = datetime.datetime.now()  ##now为datetime（即时间类型）
daystr = now.strftime("%Y-%m-%d")
basePath='/home/marvin/daily_job/logs/'+daystr+'/'
tmpPath='/home/marvin/daily_job/'
# basePath='./'


def warn_mail(sendFrom,sendTo,passwd,logs):
    '''
    发送邮件的方法
    :param sendFrom: 发送人邮箱
    :param sendTo: 收件人邮箱
    :param passwd: 发送邮箱授权码
    :param msg: 发送信息
    :return:
    '''

    msgRoot = MIMEMultipart('related')
    msgText = MIMEText(logs, 'html', 'utf-8')
    msgRoot.attach(msgText)

    msgRoot['From'] = formataddr(["marvin", sendFrom])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    msgRoot['To'] = formataddr(["邮箱警告提醒", sendTo])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msgRoot['Subject'] = "数据任务执行检查"  # 邮件的主题，也可以说是标题
    server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器，端口是465
    server.login(sendFrom, passwd)  # 括号中对应的是发件人邮箱账号、邮箱密码
    server.sendmail(sendFrom, [sendTo], msgRoot.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.quit()  # 这句是关闭连接的意思


def timeout_mail(sendFrom,sendTo,passwd):
    '''
    发送邮件的方法
    :param sendFrom: 发送人邮箱
    :param sendTo: 收件人邮箱
    :param passwd: 发送邮箱授权码
    :param msg: 发送信息
    :return:
    '''

    msgRoot = MIMEMultipart('related')
    msgText = MIMEText('''
        代码运行超时！！！！！！！<br>
        代码运行超时！！！！！！！<br>
        代码运行超时！！！！！！！<br>
    ''', 'html', 'utf-8')
    msgRoot.attach(msgText)

    msgRoot['From'] = formataddr(["marvin", sendFrom])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    msgRoot['To'] = formataddr(["邮箱警告提醒", sendTo])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msgRoot['Subject'] = "数据任务超时"  # 邮件的主题，也可以说是标题
    server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器，端口是465
    server.login(sendFrom, passwd)  # 括号中对应的是发件人邮箱账号、邮箱密码
    server.sendmail(sendFrom, [sendTo], msgRoot.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.quit()  # 这句是关闭连接的意思

def check(filename):
    li = []
    lis = set()
    with open(filename,'r') as f:
        count=1
        for line in f.readlines():
            if len(li)>=10:
                li.pop(0)
            li.append((count,filename+str(count),line))
            if 'Caused by'.lower() in line or 'Status : FAILED'.lower() in line.lower() or 'Container launch failed for container'  in line or 'Caused by: java.net.ConnectException: Call From' in line:
                # lis.append(li)
                lis|=set(li)
            count = count + 1
    # print len(lis)
    a=list(lis)
    a.sort()
    logs=''
    for log in a:
        logs+= '<br>'+str(log[1])+'\t'+log[2]
    if ''!=logs:
        return logs
    else:
        return None



if __name__ == '__main__':
    sendFrom = '2541692705@qq.com'  #
    passwd = "kpxlnuazfpowebch"  # 授权码
    filenames=['dailyhqlsqoop.loglog','dailyhql.loglog','dailysqoop.loglog','hqlpart1.log','hqlpart2.log']
    # filenames=['test.py']

    logs=[]
    for filename in filenames:
        log=check(basePath+filename)
        if log:
            logs.append(log)

    if len(logs)!=0:
        warn_mail(sendFrom, '951730482@qq.com', passwd, '<br><br>'.join(logs))

    # print a
    # for l in li:
        #     print l[0],l[1]
        # print len(li)


    # sendFrom = '2541692705@qq.com'  #
    # passwd = "kpxlnuazfpowebch"  # 授权码
    # mymail(sendFrom,'951730482@qq.com', passwd,logs)

    isTimeout=True
    with open(tmpPath+'tmp.loglog','r') as  f:
        timestr = now.strftime("%Y-%m-%d")
        for line in f.readlines():
            if u'hive to mysql结束'.encode('utf8')+timestr in line:
                isTimeout=False
    if isTimeout:
        timeout_mail(sendFrom,'951730482@qq.com', passwd)